/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.engine.function;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.extend.Environment;
import axil.api.extend.Parameters;
import axil.api.extend.Source;
import axil.framework.error.EvaluationException;
import axil.framework.localization.Message;
import axil.framework.localization.MessageContainer;
import axil.vm.opcode.Opcode;
import axil.vm.stack.IDedArguments;
import axil.vm.stack.StackFrame;

import static axil.framework.Functions.*;


/**
 * An object that represents a function as an object.
 */
public class Func extends Opcode implements Functor, IDedArguments {
	public static final AxilType type = Func_Type.object;

	private Opcode function;
	private String[] symbols;
	private int[] ids;


	/**
	 * This constructor is used only when creating anonymous instances suitable
	 * for loading the function definition. Use this with caution! This is not
	 * meant to create an executable object.
	 */
	public Func() {
	}


	public Func(Source source, String[] symbols, int[] ids, Opcode function) {
		super(source);
		this.symbols = symbols;
		this.ids = ids;
		this.function = function;
	}


	/**
	 * Relink this instruction, replacing the bad variable ID with the good
	 * variable ID. This is used when linking code that contains forward
	 * references, allowing us to compile in a single pass, but correct later.
	 */
	public void relink(int bad, int good) {
		replace(ids, bad, good);
		replace(function, bad, good);
	}


	/**
	 * Get the symbolic identifiers for all of the arguments to this function.
	 * These are used to verify integrity of the code, not used at excecution
	 * time.
	 */
	public String[] symbols() {
		return symbols;
	}


	/**
	 * Get the array of IDs representing the unique ID of each argument to a
	 * function. The array returned is never null but may be empty.
	 */
	public int[] ids() {
		return ids;
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object. Since these objects are
	 * special and not intended to be created by scripts, they are not
	 * registered types.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Dump the content of this node to the diagnostic device. This is strictly
	 * for internal diagnostics, not for application use.
	 */
	public void dump(int indent) {
		debug(indent, "FUNCTOR()");
		function.dump(indent + 1);
	}


	/**
	 * Evaluate this object in the given context and environment.
	 *
	 * @param env
	 * 	The environment in which the function is being invoked. The environment
	 * 	is never null.
	 *
	 * @param params
	 * 	The parameters to the function, which can be any Axil object. The values
	 * 	given are never null but may be the nil object (Axil.NIL).
	 */
	public AxilObject call(Environment env, Parameters params) {
		try {
			/*
			 * A functor is unusual in that evaluating the functor simply
			 * returns itself. However, calling the functor will cause the
			 * underlying function to be evaluated.
			 */
			return function.eval(env, params);
		} catch (Throwable e) {
			if (e instanceof MessageContainer) {
				throw new EvaluationException(e, (StackFrame)params,
				                              ((MessageContainer)e).message());
			}
			throw new EvaluationException(e, (StackFrame)params,
			                              new Message(axil(), "generic-runtime-error"));
		}
	}


	/**
	 * Evaluate this object in the given context and environment. A non-null
	 * object must be returned.
	 */
	protected AxilObject evaluate(Environment env, Parameters params) {
		return this;
	}


	/**
	 * Evaluate this object in the given context and environment.
	 *
	 * @param env
	 * 	The environment in which the function is being invoked. The environment
	 * 	is never null.
	 *
	 * @param params
	 * 	The parameters to the function, which can be any Axil object. The values
	 * 	given are never null but may be the nil object (Axil.NIL).
	 */
	public AxilObject eval(Environment env, Parameters params) {
		/*
		 * When evaluated, a functor always returns itself. That is because the
		 * functor is an object. Only the special call() method can actually
		 * invoke the function.
		 */
		return this;
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		/*
		 * Return a true value only if these are the exact same functor. Even
		 * if two functors contains the exact same code, we do not consider
		 * them equal unless they are the same object. If we allowed comparing
		 * the compiled code, then the behavior of a script could vary from one
		 * release to the next (due to optimization, etc).
		 */
		return this == object;
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		return "(func)";
	}
}
